const express = require('express')
const router = express.Router()
const PointsService = require('../../services/pointsService')
const auth = require('../../middleware/auth')
const { body, query, validationResult } = require('express-validator')
const logger = require('../../utils/logger')

/**
 * 管理员发放积分
 * POST /api/admin/points/award
 */
router.post('/award', [
  auth, // 这里应该是管理员认证中间件
  body('userId').isInt({ min: 1 }).withMessage('用户ID必须是正整数'),
  body('amount').isFloat({ min: 0.01 }).withMessage('积分数量必须大于0'),
  body('source').isIn(['activity', 'admin_adjust']).withMessage('积分来源无效'),
  body('description').optional().isLength({ max: 255 }).withMessage('描述长度不能超过255字符'),
  body('expireTime').optional().isISO8601().withMessage('过期时间格式无效')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const { userId, amount, source, description, expireTime } = req.body
    const adminId = req.user.id

    const pointRecord = await PointsService.awardPoints(
      userId,
      amount,
      source,
      adminId,
      description || `管理员发放积分`,
      expireTime ? new Date(expireTime) : null
    )
    
    res.json({
      success: true,
      code: 200,
      message: '发放积分成功',
      data: pointRecord
    })
  } catch (error) {
    logger.error('管理员发放积分失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: error.message || '发放积分失败'
    })
  }
})

/**
 * 管理员冻结积分
 * POST /api/admin/points/freeze
 */
router.post('/freeze', [
  auth,
  body('userId').isInt({ min: 1 }).withMessage('用户ID必须是正整数'),
  body('amount').isFloat({ min: 0.01 }).withMessage('积分数量必须大于0'),
  body('reason').isLength({ min: 1, max: 255 }).withMessage('冻结原因必须填写且不超过255字符')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const { userId, amount, reason } = req.body
    const adminId = req.user.id

    const pointRecord = await PointsService.freezePoints(userId, amount, reason, adminId)
    
    res.json({
      success: true,
      code: 200,
      message: '冻结积分成功',
      data: pointRecord
    })
  } catch (error) {
    logger.error('管理员冻结积分失败:', error)
    
    let code = 500
    let message = '冻结积分失败'
    
    if (error.message === '用户不存在') {
      code = 404
      message = '用户不存在'
    } else if (error.message === '可用积分不足') {
      code = 400
      message = '用户可用积分不足'
    }
    
    res.status(code).json({
      success: false,
      code: code,
      message: message
    })
  }
})

/**
 * 管理员解冻积分
 * POST /api/admin/points/unfreeze
 */
router.post('/unfreeze', [
  auth,
  body('userId').isInt({ min: 1 }).withMessage('用户ID必须是正整数'),
  body('amount').isFloat({ min: 0.01 }).withMessage('积分数量必须大于0'),
  body('reason').isLength({ min: 1, max: 255 }).withMessage('解冻原因必须填写且不超过255字符')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const { userId, amount, reason } = req.body
    const adminId = req.user.id

    const pointRecord = await PointsService.unfreezePoints(userId, amount, reason, adminId)
    
    res.json({
      success: true,
      code: 200,
      message: '解冻积分成功',
      data: pointRecord
    })
  } catch (error) {
    logger.error('管理员解冻积分失败:', error)
    
    let code = 500
    let message = '解冻积分失败'
    
    if (error.message === '用户不存在') {
      code = 404
      message = '用户不存在'
    } else if (error.message === '冻结积分不足') {
      code = 400
      message = '用户冻结积分不足'
    }
    
    res.status(code).json({
      success: false,
      code: code,
      message: message
    })
  }
})

/**
 * 获取用户积分详情（管理员）
 * GET /api/admin/points/user/:userId
 */
router.get('/user/:userId', [
  auth,
  query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
  query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const userId = parseInt(req.params.userId)
    if (!userId || userId < 1) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '用户ID无效'
      })
    }

    // 获取用户积分信息
    const pointsData = await PointsService.getUserPoints(userId)
    
    // 获取积分记录
    const options = {
      page: parseInt(req.query.page) || 1,
      limit: parseInt(req.query.limit) || 20
    }
    const history = await PointsService.getPointsHistory(userId, options)
    
    res.json({
      success: true,
      code: 200,
      message: '获取用户积分详情成功',
      data: {
        balance: pointsData,
        history: history
      }
    })
  } catch (error) {
    logger.error('获取用户积分详情失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: error.message || '获取用户积分详情失败'
    })
  }
})

/**
 * 获取积分统计信息（管理员）
 * GET /api/admin/points/statistics
 */
router.get('/statistics', [
  auth,
  query('startDate').optional().isISO8601().withMessage('开始日期格式无效'),
  query('endDate').optional().isISO8601().withMessage('结束日期格式无效'),
  query('userId').optional().isInt({ min: 1 }).withMessage('用户ID必须是正整数')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const options = {
      startDate: req.query.startDate,
      endDate: req.query.endDate,
      userId: req.query.userId ? parseInt(req.query.userId) : null
    }

    const statistics = await PointsService.getPointsStatistics(options)
    
    res.json({
      success: true,
      code: 200,
      message: '获取积分统计成功',
      data: statistics
    })
  } catch (error) {
    logger.error('获取积分统计失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: error.message || '获取积分统计失败'
    })
  }
})

/**
 * 刷新积分缓存
 * POST /api/admin/points/refresh-cache
 */
router.post('/refresh-cache', [
  auth,
  body('userIds').optional().isArray().withMessage('用户ID列表必须是数组'),
  body('userIds.*').optional().isInt({ min: 1 }).withMessage('用户ID必须是正整数')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const { userIds = [] } = req.body
    await PointsService.refreshPointsCache(userIds)
    
    res.json({
      success: true,
      code: 200,
      message: '刷新积分缓存成功',
      data: { refreshedCount: userIds.length || 'all' }
    })
  } catch (error) {
    logger.error('刷新积分缓存失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: error.message || '刷新积分缓存失败'
    })
  }
})

module.exports = router